package com.brotherly.framework.transaction;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

import com.brotherly.framework.http.HttpListener;
import com.brotherly.framework.http.HttpService;
import com.brotherly.geo.MapHelper;
import com.brotherly.util.URIBuilder;

public class HttpDriver implements Driver, DriverFactory
{
    public static final String type = "http";

    protected HttpService httpService = null;

    public static class DriverHttpListener implements HttpListener
    {
        public byte[] result;

        @Override
        public void result(int code, Map<String, String> headers, byte[] body)
        {
            result = body;
        }
    }

    public HttpDriver()
    {

    }

    @Override
    public Driver createInstance()
    {
        return new HttpDriver();
    }

    @Override
    public void active(Transaction transaction)
    {
        httpService = (HttpService) TransactionServiceHost.getInstance().getService(HttpService.description);
    }

    @Override
    public byte[] deal(Transaction transaction, byte[] readyData)
    {
        Map<String, String> props = transaction.getDriverProps();
        if (props == null)
            return null;

        String urlRoot = (String) props.get("url");
        String method = MapHelper.getString(props, "method");

        URIBuilder builder = new URIBuilder(urlRoot);

        Map<String, Object> headers = new HashMap<String, Object>();

        Iterator<java.util.Map.Entry<String, String>> it = props.entrySet().iterator();
        while (it.hasNext())
        {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();

            String key = entry.getKey();
            String value = entry.getValue();

            if (key.toLowerCase(Locale.ENGLISH).startsWith("header."))
            {
                String name = key.substring("header.".length());

                headers.put(name, value);
            } else if (key.toLowerCase(Locale.ENGLISH).startsWith("param."))
            {
                String name = key.substring("param.".length());

                builder.getPath().putParameter(name, value);
            }
        }

        DriverHttpListener listener = new DriverHttpListener();

        try
        {
            httpService.request(builder.toString(), method, headers, readyData, listener, true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }

        return listener.result;
    }

    @Override
    public void inactive(Transaction transaction)
    {}
}
